//
//  CrazyChatGoodsListView.m
//  webSocket
//
//  Created by 马军凯 on 2019/2/20.
//  Copyright © 2019年 ZH. All rights reserved.
//

#import "CrazyChatGoodsListView.h"
#import "CrazyChatGoodsListCell.h" //cell

@interface CrazyChatGoodsListView () <UITableViewDelegate, UITableViewDataSource>
{
    int _page;
    int _allPage;
    NSString *typeStr;
    NSArray *nameArray;
}

@property (nonatomic, strong) UITableView *goodsListTableView;
@property (nonatomic, retain) NSMutableArray *goodsListDataArray; //数据源

@end

@implementation CrazyChatGoodsListView

- (void)dealloc {
    NSLog(@"商品列表页销毁");
}

//单例
+ (instancetype)sharedDefault {
    return [[self alloc] init];
}

//初始化
- (instancetype)init {
    if (self = [super init]) {
        self.backgroundColor = [CRAZY_RGBR(114) colorWithAlphaComponent:0.5];
        //加载子视图
        [self setLayoutSubViews];
        typeStr = @"1";
        //网络请求
        dispatch_async(dispatch_get_main_queue(), ^{
            [self headRefresh];
        });
        //刷新
        [self createRefresh];
    }
    return self;
}
//加载子视图
- (void)setLayoutSubViews {
    //白色背景
    UIView *whiteBackView = [[UIView alloc] init];
    whiteBackView.frame = CGRectMake(0, CRAZY_SCREEN_HEIGHT / 3, CRAZY_SCREEN_WIDTH, CRAZY_SCREEN_HEIGHT / 3 * 2);
    whiteBackView.backgroundColor = [UIColor whiteColor];
    [self addSubview:whiteBackView];
    //取消按钮
    UIButton *cancelBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    cancelBtn.frame = CGRectMake(whiteBackView.width - 40, 0, 40, 40);
    [cancelBtn setImage:[UIImage imageNamed:@"CrazyChat_close@2x.png"] forState:UIControlStateNormal];
    [cancelBtn addTarget:self action:@selector(clickRemoveSelf) forControlEvents:UIControlEventTouchUpInside];
    [whiteBackView addSubview:cancelBtn];
    //描述
    UILabel *descripLabel = [[UILabel alloc] init];
    descripLabel.frame = CGRectMake(10, 10, whiteBackView.width - 60, 20);
    descripLabel.text = @"选择咨询商品";
    descripLabel.textColor = CRAZY_RGB(142, 148, 155);
    descripLabel.font = [UIFont systemFontOfSize:14];
    [whiteBackView addSubview:descripLabel];
    //线
    UIView *oneLineView = [[UIView alloc] init];
    oneLineView.frame = CGRectMake(0, 40, whiteBackView.width, 1);
    oneLineView.backgroundColor = CRAZY_RGBR(242);
    [whiteBackView addSubview:oneLineView];
    //按钮
    nameArray = @[@"已买到", @"浏览", @"关注", @"购物车"];
    for (int i = 0; i < nameArray.count; i++) {
        UIButton *changeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        changeBtn.frame = CGRectMake((whiteBackView.width / nameArray.count) * i, 41, whiteBackView.width / nameArray.count, 38);
        [changeBtn setTitle:nameArray[i] forState:UIControlStateNormal];
        [changeBtn setTitleColor:CRAZY_RGBR(150) forState:UIControlStateNormal];
        [changeBtn setTitleColor:[UIColor blackColor] forState:UIControlStateSelected];
        changeBtn.titleLabel.font = [UIFont systemFontOfSize:14];
        changeBtn.tag = 2000 + i;
        [changeBtn addTarget:self action:@selector(clickChangeGoodsBtn:) forControlEvents:UIControlEventTouchUpInside];
        [whiteBackView addSubview:changeBtn];
        CGSize size = [nameArray[i] sizeWithAttributes:@{NSForegroundColorAttributeName : CRAZY_RGBR(150), NSFontAttributeName : [UIFont systemFontOfSize:14]}];
        UIView *lineView = [[UIView alloc] init];
        lineView.frame = CGRectMake(0, 79, size.width, 2);
        lineView.centerX = changeBtn.centerX;
        lineView.backgroundColor = CRAZY_RGB(242, 18, 5);
        lineView.tag = 3000 + i;
        [whiteBackView addSubview:lineView];
        if (i == 0) {
            lineView.hidden = NO;
            changeBtn.selected = YES;
        } else {
            lineView.hidden = YES;
            changeBtn.selected = NO;
        }
    }
    //线
    UIView *twoLineView = [[UIView alloc] init];
    twoLineView.frame = CGRectMake(0, 81, whiteBackView.width, 1);
    twoLineView.backgroundColor = CRAZY_RGBR(242);
    [whiteBackView addSubview:twoLineView];
    //tableView
    self.goodsListTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 82, whiteBackView.width, whiteBackView.height - 82) style:UITableViewStylePlain];
    self.goodsListTableView.delegate = self;
    self.goodsListTableView.dataSource = self;
    self.goodsListTableView.estimatedRowHeight = 0;
    self.goodsListTableView.estimatedSectionHeaderHeight = 0;
    self.goodsListTableView.estimatedSectionFooterHeight = 0;
    self.goodsListTableView.showsVerticalScrollIndicator = NO;
    self.goodsListTableView.showsHorizontalScrollIndicator = NO;
    [self.goodsListTableView registerClass:[CrazyChatGoodsListCell class] forCellReuseIdentifier:@"CrazyChatGoodsListCell"];
    [whiteBackView addSubview:self.goodsListTableView];
    self.goodsListTableView.tableFooterView = [UIView new];
}

#pragma mark UITableView dataSource
//几组
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
//每组个数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.goodsListDataArray.count;
}
#pragma mark UITableView delegate
//cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    CrazyChatGoodsListCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    if (cell == nil) {
        cell = [[CrazyChatGoodsListCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"CrazyChatGoodsListCell"];
    }
    CrazyChatGoodsListDataModel *model = self.goodsListDataArray[indexPath.row];
    if (model) {
        cell.model = model;
    }
    
    return cell;
}
//cell的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 90;
}
#pragma mark separator 分割线
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        cell.separatorInset = UIEdgeInsetsMake(0, 0, 0, 0);
    }
    if ([cell respondsToSelector:@selector(setPreservesSuperviewLayoutMargins:)]) {
        cell.preservesSuperviewLayoutMargins = NO;
    }
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        cell.layoutMargins = UIEdgeInsetsZero;
    }
}
#pragma mark UITableView didselect
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    CrazyChatGoodsListDataModel *model = self.goodsListDataArray[indexPath.row];
    if (self.block) {
        self.block(model);
    }
    [self removeFromSuperview];
}


#pragma mark 改变商品的条件
- (void)clickChangeGoodsBtn:(UIButton *)sender {
    for (int i = 0; i < nameArray.count; i++) {
        UIView *oldLineView = [self viewWithTag:3000 + i];
        UIButton *oldBtn = [self viewWithTag:2000 + i];
        oldBtn.selected = NO;
        oldLineView.hidden = YES;
    }
    sender.selected = YES;
    UIView *newLineView = [self viewWithTag:3000 + (sender.tag - 2000)];
    newLineView.hidden = NO;
    
    typeStr = [NSString stringWithFormat:@"%ld", (sender.tag - 1999)];
    [self headRefresh];
}


#pragma mark 刷新
- (void)createRefresh {
    MJWeakSelf;
    self.goodsListTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [weakSelf headRefresh];
    }];
    self.goodsListTableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        [weakSelf footRefresh];
    }];
    self.goodsListTableView.mj_footer.ignoredScrollViewContentInsetBottom = CRAZY_IS_iPhoneX_up ? CRAZY_HOME_HEIGHT : 0;
}
//刷新
- (void)headRefresh {
    _page = 1;
    [self.goodsListDataArray removeAllObjects];
    [self.goodsListTableView reloadData];
    [self getGoodsListData];
}
//加载更多
- (void)footRefresh {
    if (_page > _allPage) {
        [self.goodsListTableView.mj_footer endRefreshingWithNoMoreData];
        [self.goodsListTableView.mj_footer endRefreshing];
    } else {
        [self getGoodsListData];
    }
}
//结束刷新
- (void)endRefresh {
    [self.goodsListTableView.mj_header endRefreshing];
    [self.goodsListTableView.mj_footer endRefreshing];
}

#pragma mark 网络请求
- (void)getGoodsListData {
    NSString *urlString = [NSString stringWithFormat:@"%@%@", CRAZY_CHAT_API_DOMIN, @"customer/getGoodsList"];
    NSDictionary *params = @{@"member_id" : UID, @"list_type" : typeStr, @"page" : [NSString stringWithFormat:@"%d", _page]};
    CrazyWeakSelf;
    [CrazyNetWork CrazyRequest_Post:urlString HUD:YES parameters:params success:^(NSDictionary *dic, NSString *url, NSString *Json) {
        if ([[NSString stringWithFormat:@"%@", dic[@"code"]] isEqualToString:@"0"]) {
            [weakSelf receiveGoodsListDataWith:dic[@"data"]];
        } else {
            [JKToast showWithText:dic[@"data"]];
        }
        [weakSelf endRefresh];
    } fail:^(NSError *error, NSString *url) {
        [weakSelf endRefresh];
    }];
}
//保存数据
- (void)receiveGoodsListDataWith:(NSDictionary *)dic {
    CrazyChatGoodsListModel *allModel = [[CrazyChatGoodsListModel alloc] init];
    allModel = [CrazyChatGoodsListModel objectWithKeyValues:dic];
    
    int total = [allModel.total intValue];
    int per_page = [allModel.per_page intValue];
    if (0 == total % per_page) {
        _allPage = total / per_page;
    } else {
        _allPage = total / per_page + 1;
    }
    _page = _page + 1;
    
    for (CrazyChatGoodsListDataModel *model in allModel.data) {
        [self.goodsListDataArray addObject:model];
    }
    [self.goodsListTableView reloadData];
}

#pragma mark 显示
- (void)showGoodsListView {
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    self.frame = window.bounds;
    [window addSubview:self];
}

#pragma mark 消失
- (void)clickRemoveSelf {
    [self removeFromSuperview];
}

#pragma mark 懒加载
- (NSMutableArray *)goodsListDataArray {
    if (_goodsListDataArray == nil) {
        _goodsListDataArray = [NSMutableArray array];
    }
    return _goodsListDataArray;
}

@end
